package tr.edu.yildiz.ce.dap.appagentinfra.service;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import tr.edu.yildiz.ce.dap.appagent.service.infra.ResourceManager;
import tr.edu.yildiz.ce.dap.appagent.util.AgentProperties;

public class ResourceManagerImpl implements ResourceManager {


	class ResourceFilter implements FileFilter{

		public boolean accept(File f) {
			return !(f.getName().endsWith(".class"));
		}
		
	}
	
	private void extractResources(String jarFilePath,String applicationName) throws IOException{
		String destDirPath = getResourceFolderPath();
		File destDir = new File(getApplicationResourceFolderPath(applicationName));
		JarFile jarFile = new JarFile(new File(jarFilePath));
		Enumeration enumeration = jarFile.entries();
		while (enumeration.hasMoreElements()) {
			JarEntry jarEntry = (JarEntry) enumeration.nextElement();
			File entryFile = new File(destDir.getPath() + java.io.File.separator + jarEntry.getName());
			if (jarEntry.isDirectory()){
				entryFile.mkdir();
				continue;
			}
			java.io.InputStream is = jarFile.getInputStream(jarEntry);
			java.io.FileOutputStream fos = new java.io.FileOutputStream(entryFile);
			while (is.available() > 0) {  
			   fos.write(is.read());
			}
			fos.close();
			is.close();

		}
		
	}

	private String getApplicationResourceFolderPath(String applicationName) {
		String destDirPath = getResourceFolderPath();
		String appDirPath = destDirPath + java.io.File.separator  + applicationName;
		File destDir = new File(appDirPath);
		if (!destDir.exists())
			destDir.mkdir();
		return appDirPath;
	}

	private String getResourceFolderPath() {
		String destDirPath = AgentProperties.getInstance().getResourcePath();
		if (!new File(destDirPath).exists())
			new File(destDirPath).mkdir();
		return destDirPath;
	}
	
	public void initializeResourcesFolder(String jarFilePath,String applicationName) throws Exception{
		extractResources(jarFilePath, applicationName);
	}

	public String getResourceAbsolutePath(String resourceName,String applicationName) throws Exception{
		String appDirPath = getApplicationResourceFolderPath(applicationName);
		return appDirPath + java.io.File.separator + resourceName;
	}

}
